package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.fasterxml.jackson.databind.ObjectMapper;

public class GitLogParser {

    public static void main(String[] args) throws Exception {
        String since = "2023-01-01";
        String until = "2023-02-22";

        List<Map<String, Object>> logs = getGitLogs(new File("/home/ext2/git/dqb"), since, until );

        System.out.println(logs);
        // 将结果转成 JSON 字符串并输出
        ObjectMapper mapper = new ObjectMapper();
        String jsonOutput = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(logs);
        System.out.println(jsonOutput);
    }

    public static List<Map<String, Object>> getGitLogs(File gitDir, String since, String until) throws Exception {
        List<Map<String, Object>> logList = new ArrayList<>();
        
		String delimiter = UUID.randomUUID().toString();

        // Step 1: 获取 Git log 的基础信息
        String logCommand = String.format(
                "git log --since=%s --until=%s --pretty=format:\"%%H%3$s%%an%3$s%%ae%3$s%%ad%3$s%%cn%3$s%%ce%3$s%%cd%3$s%%s\" --date=iso",
                since, until, delimiter);
        List<String> logOutput = runCommand(logCommand, gitDir);

        DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        
        for (String logLine : logOutput) {
            String[] parts = logLine.split(delimiter, 8);
            if (parts.length < 8) continue;

            // 提取基本信息
            String sha = parts[0];
            String authorName = parts[1];
            String authorEmail = parts[2];
            String authorDate = parts[3] ;
            String committerName = parts[4];
            String committerEmail = parts[5];
            String committerDate = parts[6];
            String message = parts[7];

            // Step 2: 获取每个提交的统计信息
            String statsCommand = String.format("git show --numstat --pretty=format: %s", sha);
            List<String> statsOutput = runCommand(statsCommand, gitDir);

            int additions = 0;
            int  deletions = 0;
            int files =0;
            for (String statsLine : statsOutput) {
                String[] statsParts = statsLine.split("\t");
                if (statsParts.length == 3) {
                    additions += parseIntSafe(statsParts[0]);
                    deletions += parseIntSafe(statsParts[1]);
                    files++;
                }
            }

            // 创建 JSON 对象
            Map<String, Object> logEntry = new HashMap<>();
            logEntry.put("sha", sha);

            // 作者信息
            Map<String, Object>  author = Map.of(
            	"name", authorName
            	,"email", authorEmail
            	,"date", datetimeFormat.parse(authorDate));
            logEntry.put("author", author);

            // 提交者信息
            Map<String, Object> committer = Map.of(
            	"name", committerName
            	,"email", committerEmail
            	,"date", datetimeFormat.parse(committerDate));
            logEntry.put("committer", committer);

            // 提交信息
            logEntry.put("message", message);

            // 统计信息
            Map<String, Object> stats = Map.of("files", files
            		,"additions", additions
					,"deletions", deletions
					,"total", additions + deletions);
            logEntry.put("stat", stats);

            logList.add(logEntry);
        }

        return logList;
    }

    // Helper 方法：运行 Shell 命令
    private static List<String> runCommand(String command, File dir) throws Exception {
        List<String> output = new ArrayList<>();
        ProcessBuilder builder = new ProcessBuilder()
        		.command("bash", "-c", command)
        		.directory(dir);
        Process process = builder.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.add(line);
            }
        }

        process.waitFor();
        return output;
    }

    // Helper 方法：安全地解析数字
    private static int parseIntSafe(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}
